package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"order-mgmt-sys/cache"
	"order-mgmt-sys/models"
	"order-mgmt-sys/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户或密码不能为空",
		})
		return
	}

	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "没有找到该用户",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}

func UserAddRole(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色或权限id不能为空",
		})
		return
	}

	data := models.UserRole{
		Model: gorm.Model{},
		Uid:   rid,
		Rid:   nid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色分配权限失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色分配权限成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))

	/*
		   SELECT
		  *
		FROM
		  roles
		  JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	var role []models.Role
	models.DB.Table("roles").
		Joins("JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).
		Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"data": role,
	})

}

func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色和权限id不能为空",
		})
		return
	}

	data := models.RoleNode{
		Model: gorm.Model{},
		Rid:   rid,
		Nid:   nid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "权限关联失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "权限关联成功",
	})
	return

}

func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	/*
		SELECT
		  *
		FROM
		  nodes
		  JOIN role_nodes ON nodes.id = role_nodes.nid
		  WHERE role_nodes.rid = 1
	*/
	var node []models.Node
	models.DB.Table("nodes").
		Joins("JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid = ?", rid).
		Find(&node)

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  node,
	})

}

func GoodAdd(c *gin.Context) {
	goodCode := c.PostForm("goodCode")
	goodName := c.PostForm("goodName")
	goodType := c.PostForm("goodType")
	goodPrice, _ := strconv.Atoi(c.PostForm("goodPrice"))
	if goodCode == "" || goodName == "" || goodType == "" || goodPrice == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Goods{
		Model:     gorm.Model{},
		GoodCode:  goodCode,
		GoodName:  goodName,
		GoodType:  goodType,
		GoodPrice: goodPrice,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加数据失败",
		})
		return
	}

	var good models.Goods
	redis_key := "good_add_" + strconv.Itoa(int(good.ID))
	models.DB.Where("id = ?", good.ID).First(&good)
	jsonData, _ := json.Marshal(good)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加数据成功",
	})
	return

}

func OrderAdd(c *gin.Context) {
	orderNo := c.PostForm("orderNo")
	orderForm := c.PostForm("orderForm")
	orderTo := c.PostForm("orderTo")
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	if orderNo == "" || orderForm == "" || orderTo == "" || gid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Order{
		Model:     gorm.Model{},
		OrderNo:   orderNo,
		OrderForm: orderForm,
		OrderTo:   orderTo,
		Gid:       gid,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "订单添加失败",
		})
		return
	}

	var order models.Order
	redis_key := "order_add" + strconv.Itoa(int(order.ID))
	models.DB.Where("id = ?", order.ID).Find(&order)
	jsonData, _ := json.Marshal(order)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "订单添加成功",
	})
	return

}

func GoodOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	/*
		        SELECT
			  orders.id AS OrderID,
			  goods.good_code AS GoodCode,
			  goods.good_name AS GoodName,
			  goods.good_type AS GoodType,
			  goods.good_price AS GoodPrice,
			  orders.order_no AS OrderNo,
			  orders.order_form AS OrderForm,
			  orders.order_to AS  OrderTo
			FROM
			  orders
			  LEFT JOIN goods ON orders.gid = goods.id
	*/
	var goodOrderList []models.GoodOrderList
	redis_key := "good_order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN goods ON orders.gid = goods.id").
			Select(
				"orders.id AS OrderID",
				"goods.good_code AS GoodCode",
				"goods.good_name AS GoodName",
				"goods.good_type AS GoodType",
				"goods.good_price AS GoodPrice",
				"orders.order_no AS OrderNo",
				"orders.order_form AS OrderForm",
				"orders.order_to AS  OrderTo",
			).
			Offset(offset).
			Limit(size).
			Find(&goodOrderList)

		jsonData, _ := json.Marshal(goodOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goodOrderList)
	}

	var total int64
	models.DB.Model(&models.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "订单列表展示成功",
		"total": total,
		"data":  goodOrderList,
	})
	return

}

func GoodOrderDetail(c *gin.Context) {
	id := c.Query("id")

	/*
			        SELECT
				  orders.id AS OrderID,
				  goods.good_code AS GoodCode,
				  goods.good_name AS GoodName,
				  goods.good_type AS GoodType,
				  goods.good_price AS GoodPrice,
				  orders.order_no AS OrderNo,
				  orders.order_form AS OrderForm,
				  orders.order_to AS  OrderTo
		          WHERE orders.id = 1
				FROM
				  orders
				  LEFT JOIN goods ON orders.gid = goods.id
	*/
	var goodOrderList models.GoodOrderList
	redis_key := "good_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN goods ON orders.gid = goods.id").
			Select(
				"orders.id AS OrderID",
				"goods.good_code AS GoodCode",
				"goods.good_name AS GoodName",
				"goods.good_type AS GoodType",
				"goods.good_price AS GoodPrice",
				"orders.order_no AS OrderNo",
				"orders.order_form AS OrderForm",
				"orders.order_to AS  OrderTo",
			).
			Where("orders.id = ?", id).
			Find(&goodOrderList)

		jsonData, _ := json.Marshal(goodOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goodOrderList)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "订单列表展示成功",
		"data": goodOrderList,
	})
	return

}
